package com.bingbing.bingbingmall.order.listener;

import com.bingbing.bingbingmall.order.service.OrderService;
import com.bingbing.common.constant.AuthServerConstant;
import com.bingbing.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;


@Controller
public class OrderPayedListener {

    @Autowired
    OrderService orderService;
    /**
     * 支付宝成功异步通知
     * @param
     * @return
     */
    @PostMapping("/payed/notify")
    public String handleAlipayed(String password, String orderSn, HttpSession session, RedirectAttributes redirectAttributes){

        MemberRespVo data =(MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        //1、获取到数据库的password  $2a$10$2xOI1.2DTQxpWeWd3Rk0qOVPTpauodlYkafTjNb4LOMuS1zBEZc5K
        String passwordDb = data.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //2、密码匹配
        System.out.println("_____________________________________");
        System.out.println(password);
        System.out.println(passwordDb);
        boolean matches = passwordEncoder.matches(password, passwordDb);

        if(matches){
            System.out.println("签名验证成功...");
            String result = orderService.handlePayResult(orderSn);
            if(result == "success"){
                return "redirect:http://localhost:8000/memberOrder.html";
            } else if (result == "error"){
                //redirectAttributes.addFlashAttribute("msg","该订单已经完成支付！");
                return "redirect:http://localhost:8000/memberOrder.html?message=0";
            }
            System.out.println("签名验证失败...");
            redirectAttributes.addFlashAttribute("msg","系统内部异常，请重新支付！");
            return "redirect:http://localhost:9000/toTrade";
        }else {
            System.out.println("签名验证失败...");
            redirectAttributes.addFlashAttribute("msg","支付密码错误，请重新支付！");
            return "redirect:http://localhost:9000/toTrade";
        }

    }
}
